package com.sk.compiler.info.autowire;


import com.sk.compiler.info.NameInfo;

import java.util.List;
import java.util.Set;

public class BuilderUtils {

    public static String buildAutowire(NameInfo nameInfo, AutowireInfo autowireInfo) {
        StringBuilder builder = new StringBuilder();
        builder.append("package " + nameInfo.getPackageName() + ";\n" +
                "\n" +
                "import com.sk.api.interfaces.AutowireHelper;\n" +
                "import com.sk.api.interfaces.BaseFactory;\n" +
                "import java.util.Map;\n");
        Set<String> packages = autowireInfo.getPackages();
        for (String item : packages) {
            builder.append("import " + item + ";\n");
        }
        builder.append("\n" +
                "public class " + nameInfo.getNewClassName() + " implements AutowireHelper<" + nameInfo.getClassName() + "> {\n" +
                "\n" +
                "    @Override\n" +
                "    public void autowire(" + nameInfo.getClassName() + " target, Map<String, BaseFactory> map) {\n");
        List<FieldInfo> fieldInfos = autowireInfo.getFieldInfos();
        for (FieldInfo fieldInfo:fieldInfos){
            builder.append("        target." + fieldInfo.getFieldName() + "= (" + fieldInfo.getType()
                    + ") map.get(\"" + fieldInfo.getKey() + "\").getObject(map);\n");
        }
        List<MethodInfo> methodInfos = autowireInfo.getMethodInfos();
        for (MethodInfo methodInfo:methodInfos){
            builder.append("        target."+methodInfo.getMethodName()+"("+biuldParam(methodInfo.getParamInfos())+");\n");
        }
        builder.append("    }\n" +
                "\n" +
                "}");
        return builder.toString();
    }

    private static String biuldParam(List<ParamInfo> paramInfos) {
        StringBuilder builder=new StringBuilder();
        for (ParamInfo paramInfo:paramInfos){
            builder.append("("+paramInfo.getType()+") map.get(\""+paramInfo.getKey()+"\").getObject(map),");
        }
        return builder.substring(0,builder.length()-1);
    }

}